package cn.yiyuan;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class JuheBirthEightQuery {

    public static void main(String[] args) {
        // Replace "YOUR_API_KEY" with your actual API key
        String apiKey = "YOUR_API_KEY";

        // Replace these values with the date and time you want to query
        int year = 2021;
        int month = 1;
        int day = 15;
        int hour = 12;

        // Construct the API URL
        String apiUrl = "http://apis.juhe.cn/birthEight/query?key=" + apiKey +
                "&year=" + year + "&month=" + month + "&day=" + day + "&hour=" + hour;

        try {
            // Create a URL object
            URL url = new URL(apiUrl);

            // Open a connection to the URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Set the request method to GET
            connection.setRequestMethod("GET");

            // Get the response code
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                // Read the response
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }

                reader.close();

                // Parse the JSON response using Jackson
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(response.toString());

                // Access the result field
                JsonNode resultNode = jsonNode.get("result");

                // Access specific fields from the result
                String animal = resultNode.get("Animal").asText();
                String astro = resultNode.get("astro").asText();

                // Print the extracted information
                System.out.println("Animal: " + animal);
                System.out.println("Astro: " + astro);
            } else {
                System.out.println("Error: HTTP request failed with code " + responseCode);
            }

            // Close the connection
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
